package com.service.lotterySystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.config.utils.*;
import com.service.lotterySystem.dto.ExportLQaDto;
import com.service.lotterySystem.dto.QueryQaInfoDto;
import com.service.lotterySystem.entity.LQa;
import com.service.lotterySystem.dao.LQaDao;
import com.service.lotterySystem.service.LQaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷调查，用户留资(LQa)表服务实现类
 *
 * @author makejava
 * @since 2022-03-02 15:49:39
 */
@Service("lQaService")
public class LQaServiceImpl implements LQaService {
    @Value("${spring.filePath}")
    String filePath;
    @Value("${spring.fileUrl}")
    String fileUrl;

    @Resource
    private LQaDao lQaDao;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public LQa queryById(String id) {
        return this.lQaDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<LQa> queryAllByLimit(int offset, int limit) {
        return this.lQaDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param lQa 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public LQa insert(LQa lQa) throws Exception {
        int insert = this.lQaDao.insert(lQa);
        if (insert  > 0) {
            return lQa;
        }else
        {
            //推荐：在业务层将异常抛出
            redisUtil.leftPush("qa", JsonXMLUtils.obj2json(lQa));
            throw new RuntimeException("发生异常了..");
        }

    }

    /**
     * 修改数据
     *
     * @param lQa 实例对象
     * @return 实例对象
     */
    @Override
    public LQa update(LQa lQa) {
        this.lQaDao.update(lQa);
        return this.queryById(lQa.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.lQaDao.deleteById(id) > 0;
    }

    @Override
    public Map<String,Object> findQaInfo(String userId, Integer page, Integer pageSize) {
        LQa lQa = new LQa();
        if (StringUtils.isEmpty(userId)) {
            PageHelper.startPage(page,pageSize);
        }else {
            lQa.setoId(userId);
        }
        Map<String,Object> map = new HashMap<>(16);
        List<LQa> lQaList = lQaDao.queryAllByTime(lQa);
        PageInfo<LQa> pageInfo = new PageInfo(lQaList);
        map.put("list",pageInfo.getList());
        map.put("pageSize",pageSize);
        map.put("pageIndex",page);
        map.put("totalRecords",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        return map;
    }

    /**
     * 导出用户资讯信息
     * @return
     */
    @Override
    public Result exportQaInfo(String userId, String operateName, String startDate, String endDate) {
        LQa lQa = new LQa();
        List<LQa> lQaList = new ArrayList<>();
        if (!StringUtils.isEmpty(userId)) {
            lQa.setoId(userId);
        }
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) ) {
            startDate = startDate.replaceAll("/","-");
            endDate = endDate.replaceAll("/","-");
            endDate = DateUtil.datetoString(DateUtil.dateFour(endDate));
            lQa.setCompanyName(startDate);
            lQa.setRegion(endDate);
            lQaList = lQaDao.queryAllByTime2(userId,startDate,endDate);
        }else {
            lQaList = lQaDao.queryAllByTime(lQa);
        }
        if (null != lQaList || lQaList.size()>0)
        {
            List<ExportLQaDto> exportLQaDtos = ModelMapperUtil.strictMapList(lQaList, ExportLQaDto.class);
            exportLQaDtos.stream().forEach(exportLQaDto -> exportLQaDto.setOperateName(operateName));
            long millis = System.currentTimeMillis();
            EasyExcel.write(filePath+"服务咨询信息"+millis+".xlsx", ExportLQaDto.class).sheet().doWrite(exportLQaDtos);
            return Result.ok().setData(fileUrl+"服务咨询信息"+millis+".xlsx");
        }
        return Result.failure("当前无服务咨询信息");
    }

    /**
     * 高级筛选
     * @param page
     * @param pageSize
     * @param condition
     * @return
     */
    @Override
    public Map<String, Object> queryInfoByCondition(String userId, Integer page, Integer pageSize, String condition) {
        Map<String,Object> map = new HashMap<>(16);
        LQa lQa = new LQa();
        if (!StringUtils.isEmpty(userId)) {
            lQa.setoId(userId);
        }
        PageHelper.startPage(page,pageSize);
        List<LQa> lQaList = lQaDao.queryByCondition(condition,userId);
        PageInfo<LQa> pageInfo = new PageInfo(lQaList);
        map.put("list",pageInfo.getList());
        map.put("pageSize",pageSize);
        map.put("pageIndex",page);
        map.put("totalRecords",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        return map;
    }

    @Override
    public Map<String, Object> queryInfoByTimeOrRegion(String userId, Integer page, Integer pageSize, QueryQaInfoDto queryQaInfoDto) {
        Map<String,Object> map = new HashMap<>(16);
        PageHelper.startPage(page,pageSize,"add_time DESC");
        List<LQa> lQaList = new ArrayList<>();
        if (queryQaInfoDto.getBeginTime() != null && queryQaInfoDto.getEndTime() != null) {
            queryQaInfoDto.setEndTime(DateUtil.dateFour(DateUtil.datetoString(queryQaInfoDto.getEndTime())));
            lQaList =  lQaDao.queryInfoByTimeOrRegion(userId,queryQaInfoDto.getRegion(),queryQaInfoDto.getBeginTime(),queryQaInfoDto.getEndTime());
        }else {
            lQaList = lQaDao.queryInfoByTimeOrRegion(userId,queryQaInfoDto.getRegion(),null,null);
        }
        PageInfo<LQa> pageInfo = new PageInfo(lQaList);
        map.put("list",pageInfo.getList());
        map.put("pageSize",pageSize);
        map.put("pageIndex",page);
        map.put("totalRecords",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        return map;
    }
}
